<?php
import('ORG.Util.Function');
import('@.Org.UserTool');
import('@.Org.FlowTool');
import('@.Org.PHPMailer'); /*邮件插件*/
//import('@.Org.Message'); /*短信插件*/

class UserAction extends CommonAction{

	public function _initialize(){		
		parent::_initialize();
		//判断用户是否登陆,否则跳转到登陆页面
		if(empty($_SESSION['user_id'])){
			$this->redirect('/pass/login');
		}
		//titile
		$this->assign("global_title",		"用户中心");
		
		$this->assign("layout_header","Library:user_header");
	}
	
	/**
	 * 用户中心
	 * Enter description here ...
	 */
    public function info(){
    	if ($rank = get_rank_info()){
	        $this->assign( b'rank_name', sprintf( L('your_level'), $rank['rank_name']) );
	        if ( !empty($rank['next_rank_name']) ){
	            $this->assign('next_rank_name', sprintf( $GLOBALS['_LANG']['next_level'], $rank['next_rank'] ,$rank['next_rank_name']) );
	        }
	    }
	    $this->assign('info',        get_user_default($user_id));
	    $this->assign('user_notice', $GLOBALS['_CFG']['user_notice']);
	    $this->assign('prompt',      get_user_prompt($user_id));
	    // 分成规则
	    //$affiliate 		= 	unserialize($GLOBALS['_CFG']['affiliate']);
		//$this->assign('affiliate', $affiliate);
	    $this->assign('action',      'info');
		$this->display('user_info');
    }
    
    /**
     * 用户中心
     * @param	
     * 
     */
    public function profile(){	
    	$user_id 				=	$_SESSION['user_id'];    	
	    $user_info 				= 	get_profile($user_id);
		/* 取出注册扩展字段 */
	    $sql 					= 	'SELECT * FROM ' . 'ybr_reg_fields'  . ' WHERE type < 2 AND display = 1 ORDER BY dis_order, id';
	    $extend_info_list 		= 	M()->query($sql);
	
	    $sql 					= 	'SELECT reg_field_id, content ' .
						          	'FROM ' . 'ybr_reg_extend_info'  .
						          	" WHERE user_id = $user_id";
	    $extend_info_arr 		= 	M()->query($sql);
	
	    $temp_arr 				= 	array();
	    foreach ($extend_info_arr AS $key => $val){
	    	$temp_arr[$val['reg_field_id']] = $val['content'];
	    }
		
	    foreach ($extend_info_list AS $key => $val){
	        switch ($val['id']){
	            case 1:     $extend_info_list[$key]['content'] = $user_info['msn']; break;
	            case 2:     $extend_info_list[$key]['content'] = $user_info['qq']; break;
	            case 3:     $extend_info_list[$key]['content'] = $user_info['office_phone']; break;
	            case 4:     $extend_info_list[$key]['content'] = $user_info['home_phone']; break;
	            case 5:     $extend_info_list[$key]['content'] = $user_info['mobile_phone']; break;
	            default:    $extend_info_list[$key]['content'] = empty($temp_arr[$val['id']]) ? '' : $temp_arr[$val['id']] ;
	        }
	    }	
	    $this->assign('extend_info_list', 	$extend_info_list);
	    $this->assign('action',      		'profile');
	    /* 密码提示问题 */
	    $this->assign('passwd_questions',  	L('passwd_questions'));	
	    $this->assign('profile', 			$user_info);
	    $this->display('user_profile');
    }
    
    /**
     * 用户订单
     * @param
     * 
     */
    public function order_list(){
    	$user_id 			=	$_SESSION['user_id'];    	
    	$CommonModel		=	new CommonModel();
	
	    $record_count 		= 	$CommonModel->getOne("SELECT COUNT(*) FROM " . 'ybr_order_info' . " WHERE user_id = '$user_id'");
	
	    $orders 			= 	get_user_orders($user_id);	    
	    $merge  			= 	get_user_merge($user_id);
	
	    $this->assign('merge',  		$merge);
	    $this->assign('orders', 		$orders);
	    $this->assign('action',      	'order_list');
	    
    	$this->display('user_order_list');
    }
    
    /**
     * 订单详情
     * Enter description here ...
     */
    public function order_detail(){    	
    	$CommonModel		=	new CommonModel();    	
    	$PaymentModel		=	new PaymentModel();    	
	    $order_id 			= 	isset($_GET['order_id']) ? intval($_GET['order_id']) : 0;
		
	    if ($order_id <= 0){
	        $this->error($GLOBALS['_LANG']['invalid_order_id'],U('user/order_list'));
	    }
	    // 判断订单是否存在
	    $order_is_exists	=	$CommonModel->getOne("select count(*) from ybr_order_info");
	    if(!$order_is_exists){
	    	$this->error("该订单不存在",U('user/order_list'));
	    }	    
	    //订单详情
	    $order 				= 	get_order_detail($order_id, $user_id);	    
	    //收获地址
	    $order['country']	=	M('Region')->where("region_id='{$order['country']}'")->getField('region_name');	    
	    $order['province']	=	M('Region')->where("region_id='{$order['province']}'")->getField('region_name');
	    $order['city']		=	M('Region')->where("region_id='{$order['city']}'")->getField('region_name');
	    $order['district']	=	M('Region')->where("region_id='{$order['district']}'")->getField('region_name');
	    
	    if ($order === false){
			$this->error($GLOBALS['_LANG'],U('user/order_list'));
	    }    	    
	    //是否显示添加到购物车 
	    if ($order['extension_code'] != 'group_buy' && $order['extension_code'] != 'exchange_goods'){
	        $this->assign('allow_to_cart', 1);
	    }
	
	    //订单商品
	    $goods_list 		= 	order_goods($order_id);
	    foreach ($goods_list AS $key => $value){
	        $goods_list[$key]['market_price'] 	= 	price_format($value['market_price'], false);
	        $goods_list[$key]['goods_price']  	= 	price_format($value['goods_price'], false);
	        $goods_list[$key]['subtotal']     	= 	price_format($value['subtotal'], false);
	    }
	
	     //设置能否修改使用余额数
	    if ($order['order_amount'] > 0){
	        if ($order['order_status'] == OS_UNCONFIRMED || $order['order_status'] == OS_CONFIRMED){
	            $user 							= 	user_info($order['user_id']);
	            if ($user['user_money'] + $user['credit_line'] > 0){
	                $this->assign('allow_edit_surplus', 1);
	                $this->assign('max_surplus', sprintf($GLOBALS['_LANG']['max_surplus'], $user['user_money']));
	            }
	        }
	    }	    
	    //收货人信息
	    $consignee			=	M('UserAddress')->where("address_id='{$order['adress_id']}'")->find();
	    //支付方式	
	    $payment			=	$PaymentModel->get_payment_byid($order['pay_id']);
	    $order['pay_code']	=	$payment['pay_code'];	
	    $order['pay_name']	=	$payment['pay_name'];	
	    
	    /* 未发货，未付款时允许更换支付方式 */
//	    if ($order['order_amount'] > 0 && $order['pay_status'] == PS_UNPAYED && $order['shipping_status'] == SS_UNSHIPPED){
//	        //$payment_list 						= 	available_payment_list(false, 0, true);
//	        $payment_list 						= 	available_payment_list(true, 0, false); // 支持货到付款
//	        
//	        /* 过滤掉当前支付方式和余额支付方式 */
//	        if(is_array($payment_list)){
//	            foreach ($payment_list as $key => $payment){
//	                /*if ($payment['pay_id'] == $order['pay_id'] || $payment['pay_code'] == 'balance'){
//	                    unset($payment_list[$key]);
//	                }*/
//	            	/* 过滤掉除货到付款的其他三种支付方式 */
//	            	if( $payment['pay_id'] == $order['pay_id'] )
//	            		continue;
//	            	else
//	            		unset($payment_list[$key]);
//	            }
//	        }
//	        $this->assign('payment_list', $payment_list);
//	    }
	    
	    /* 订单 支付 配送 状态语言项 */
	    $order['order_status'] 					= 	$GLOBALS['_LANG']['os'][$order['order_status']];
	    $order['pay_status'] 					= 	$GLOBALS['_LANG']['ps'][$order['pay_status']];
	    $order['shipping_status'] 				= 	$GLOBALS['_LANG']['ss'][$order['shipping_status']];
	
	    $this->assign('order',      $order);
	    $this->assign('goods_list', $goods_list);
    	$this->assign('action',     'order_list');
    	$this->display('user_order_detail');
    }
    
    /**
     * 取消订单
     * Enter description here ...
     */
    public function cancel_order(){    	
	    $order_id	= 	isset($_GET['order_id']) ? intval($_GET['order_id']) : 0;	
	    if (cancel_order($order_id, $user_id)){
	        $this->success('取消订单成功',U('user/order_list'));
	    }
	    else{
	        $this->error('订单取消失败',U('user/order_list'));
	    }	
    }    
    
    /**
     * 收获地址
     * @param
     * 
     */
    public function address_list(){   
    	$CommonModel		=	new CommonModel();	    	
    	$UserModel			=	new UserModel();
    	$user_id 			=	$_SESSION['user_id'];	    	
	    //获取默认收货ID
	    $address_id  		= 	$CommonModel->getOne("SELECT address_id FROM " . 'ybr_users' . " WHERE user_id='$user_id'");
	    //获得用户所有的收货人信息 
	    $consignee_list 	=	$UserModel->get_address_list($_SESSION['user_id']);
	    $default_consigee	=	array();	 
	    foreach ($consignee_list AS $k => $consignee){
	        //将默认的地址放在前面 
	        if($consignee['address_id'] == $address_id ){
	        		$default_consigee	=	$consignee;
	        		unset($consignee_list[$k]); //去掉默认地址排序的位置
	        }
	    }	
	    //取得国家列表、商店所在国家、商店所在国家的省列表
	    $this->assign('country_list',   	get_regions());
	    $this->assign('shop_province_list', get_regions(1, $GLOBALS['_CFG']['shop_country']));
	    //将默认收获地址放在前面
	    if(!empty($default_consigee)){
	    	array_unshift($consignee_list,$default_consigee);	
	    }
	    $this->assign('consignee_list', 	$consignee_list);	   
	    $this->assign('real_goods_count', 	1);
	    $this->assign('shop_country',     	$GLOBALS['_CFG']['shop_country']);
	    $this->assign('shop_province',    	get_regions(1, $GLOBALS['_CFG']['shop_country']));	    
	    $this->assign('province_list',    	get_regions(1, $GLOBALS['_CFG']['shop_country']));
	    $this->assign('address',          	$address_id);
	    $this->assign('city_list',        	$city_list);
	    $this->assign('district_list',    	$district_list);	    
	    $this->assign('currency_format',  	$GLOBALS['_CFG']['currency_format']);
	    $this->assign('integral_scale',   	$GLOBALS['_CFG']['integral_scale']);
	    $this->assign('name_of_region',   	array($GLOBALS['_CFG']['name_of_region_1'], $GLOBALS['_CFG']['name_of_region_2'], $GLOBALS['_CFG']['name_of_region_3'], $GLOBALS['_CFG']['name_of_region_4']));
	    $this->assign('action',      	  	'address_list');	    
	    $this->assign('action_text',     	'+新增收获地址');	    
    	$this->display('user_address_list');
    }
    
    /**
     * 修改收获地址
     * Enter description here ...
     
    public function mod_consignee_ok(){		
    	$user_id		=	$_SESSION['user_id'];    	
	    $address = array(
	        'user_id'    	=> $user_id,
	        'address_id' 	=> intval($_POST['address_id']),
	        'country'    	=> isset($_POST['country'])   ? intval($_POST['country'])  : 0,
	        'province'   	=> isset($_POST['province'])  ? intval($_POST['province']) : 0,
	        'city'       	=> isset($_POST['city'])      ? intval($_POST['city'])     : 0,
	        'district'   	=> isset($_POST['district'])  ? intval($_POST['district']) : 0,
	        'address'    	=> isset($_POST['address'])   ? compile_str(trim($_POST['address']))    : '',
	        'consignee'  	=> isset($_POST['consignee']) ? compile_str(trim($_POST['consignee']))  : '',
	        'email'      	=> isset($_POST['email'])     ? compile_str(trim($_POST['email']))      : '',
	        'tel'        	=> isset($_POST['tel'])       ? compile_str(make_semiangle(trim($_POST['tel']))) : '',
	        'mobile'     	=> isset($_POST['mobile'])    ? compile_str(make_semiangle(trim($_POST['mobile']))) : '',
	        'best_time'  	=> isset($_POST['best_time']) ? compile_str(trim($_POST['best_time']))  : '',
	        'sign_building' => isset($_POST['sign_building']) ? compile_str(trim($_POST['sign_building'])) : '',
	        'zipcode'       => isset($_POST['zipcode'])       ? compile_str(make_semiangle(trim($_POST['zipcode']))) : '',
	    );
		
	    if (update_address($address)){
	    	if($this->isAjax()){
	    		//$this->ajaxReturn(1,'添加收获地址成功',1);
	    		$template	=	'Flow:m_address_list.html';
	    		$this->fetch();
	    		
	    	}	    	
	        //show_message(, $_LANG['address_list_lnk'], 'user.php?act=address_list');
	        $this->success( $GLOBALS['_LANG']['edit_address_success'],u('user/address_list') );
	    }
    }
    */
    
    /**
     * 收获人管理
     * 
     */
    public function ajaxc_consignee(){    	
    	$UserModel		=	new UserModel();  
    	$CommonModel	=	new CommonModel();  	
    	$user_id		=	$_SESSION['user_id'];
    	$action			=	$_REQUEST['act'];
    	
    	switch($action){
    		case 'del':
    			$address_id 	= 	intval($_REQUEST['address_id']);
    			$result			=	$UserModel->del_address_byId($address_id,$user_id); 
    			$this->ajaxReturn(1,$result,1);   			  			
    		break;    		
    		default:
		    	$address = array(
			        'user_id'    	=> $user_id,
			        'address_id' 	=> intval($_POST['address_id']),
			        'country'    	=> 1,//默认China
			        'province'   	=> isset($_POST['province'])  ? intval($_POST['province']) : 0,
			        'city'       	=> isset($_POST['city'])      ? intval($_POST['city'])     : 0,
			        'district'   	=> isset($_POST['district'])  ? intval($_POST['district']) : 0,
			        'address'    	=> isset($_POST['address'])   ? compile_str(trim($_POST['address']))    : '',
			        'consignee'  	=> isset($_POST['consignee']) ? compile_str(trim($_POST['consignee']))  : '',
			        'email'      	=> isset($_POST['email'])     ? compile_str(trim($_POST['email']))      : '',
			        'tel'        	=> isset($_POST['tel'])       ? compile_str(make_semiangle(trim($_POST['tel']))) : '',
			        'mobile'     	=> isset($_POST['mobile'])    ? compile_str(make_semiangle(trim($_POST['mobile']))) : '',
			        'best_time'  	=> isset($_POST['best_time']) ? compile_str(trim($_POST['best_time']))  : '',
			        'sign_building' => isset($_POST['sign_building']) ? compile_str(trim($_POST['sign_building'])) : '',
			        'zipcode'       => isset($_POST['zipcode'])   ? compile_str(make_semiangle(trim($_POST['zipcode']))) : '',
			    );
			    //国,省,市/县,区,名,手机
				if(empty($address['country'])){ $this->ajaxReturn(1,'国家不能为空',1); }    	
		    	if(empty($address['province'])){ $this->ajaxReturn(1,'省份不能为空',1); }
		    	if(empty($address['city'])){ $this->ajaxReturn(1,'市/县不能为空',1); }
		    	if(empty($address['district'])){ $this->ajaxReturn(1,'地区不能为空',1); }
		
			    /* 获取默认收货ID */
			    $address_id  		= 	$CommonModel->getOne("SELECT address_id FROM " . 'ybr_users' . " WHERE user_id='$user_id'");			    
			    if(update_address($address)){
			    	$consignee_list		=	$UserModel->get_address_list($_SESSION['user_id']);
					$default_consigee	=	array();	
					foreach ($consignee_list AS $k => $consignee){	    	
				        //将默认的地址放在前面 
				        if($consignee['address_id'] == $address_id ){
				        		$default_consigee	=	$consignee;
				        		unset($consignee_list[$k]); //去掉默认地址排序的位置
				        }
				    }
					//将默认收获地址放在前面
			    	array_unshift($consignee_list,$default_consigee);			    
			    	$this->assign("consignee_list",$consignee_list);
			    	
			    	$template	=	'User:l_address_list';
			    	$html		=	$this->fetch($template);
			    	$this->ajaxReturn(1,$html,1);
			    }
    		break;
    	}
    }
    
    public function mod_consignee(){
    	$UserModel		=	new UserModel();  
    	$CommonModel	=	new CommonModel();  	
    	$user_id		=	$_SESSION['user_id'];
    	$address_id		= 	intval($_REQUEST['address_id']);    	
    	$consignee_info	=	$UserModel->get_address_byid($address_id, $user_id);
    	
    	$this->assign('province_list',    	get_regions(1, $GLOBALS['_CFG']['shop_country']));
    	$this->assign('city_list', 		   	get_regions(2, $consignee_info['province']));
    	$this->assign('district_list',    	get_regions(3, $consignee_info['city']));
    	$this->assign('consignee_info',    	$consignee_info);
		$this->assign('action_text',     	'确认修改');
    	$this->assign('act',   			 	'mod');
    	$template		=	"User:l_add_address";
    	$html			=	$this->fetch($template);    	
    	$this->ajaxReturn(1,$html,1);
    }
    
    
    /**
     * 删除收获地址
     * Enter description here ...
     */
    public function remove_consignee(){    			
	    $consignee_id 		= 	intval($_GET['id']);	
	    if (drop_consignee($consignee_id)){
	       	$this->success('删除成功',U('user/address_list'));
	    }
	    else{
	        $this->error($GLOBALS['_LANG']['del_address_false'],U('user/address_list'));
	    }
    }
    
    /**
     * 收藏
     * @param
     */
    public function collect(){ }
    
    /**
     * 用户留言
     * @param
     * 
     */
    public function message_list(){
			
    	$CommonModel			=	new CommonModel();
    	$user_id 				=	$_SESSION['user_id']; 
    	
	    $order_id 				= 	empty($_GET['order_id']) ? 0 : intval($_GET['order_id']);
	    $order_info 			= 	array();
	
	    /* 获取用户留言的数量 */
	    if ($order_id){
	        $sql 				= 	"SELECT COUNT(*) FROM " . 'ybr_feedback' .
	                				" WHERE parent_id = 0 AND order_id = '$order_id' AND user_id = '$user_id'";
	        $order_info 		= 	$CommonModel->getRow("SELECT * FROM " . 'ybr_order_info' . " WHERE order_id = '$order_id' AND user_id = '$user_id'");
	        $order_info['url'] 	= 	'user.php?act=order_detail&order_id=' . $order_id;
	    }
	    else{
	        $sql 				= 	"SELECT COUNT(*) FROM " .'ybr_feedback' .
	           						" WHERE parent_id = 0 AND user_id = '$user_id' AND user_name = '" . $_SESSION['user_name'] . "' AND order_id=0";
	    }
	
	    $record_count 			= 	$CommonModel->getOne($sql);
	    $act 					= 	array('act' => $action);
	
	    if ($order_id != ''){
	        $act['order_id'] 	= 	$order_id;
	    }
	    
	    $message_list			=	get_message_list($user_id, $_SESSION['user_name'], $order_id);
	    $this->assign('message_list', 	$message_list);
	    $this->assign('order_info',   	$order_info);
	    $this->assign('action',   		message_list);
    	
    	$this->display('user_message_list');
    }
    
    /**
     * 处理添加留言
     * Enter description here ...
     */
    public function add_message_ok(){
	
	    $message = array(
	        'user_id'     => $user_id,
	        'user_name'   => $_SESSION['user_name'],
	        'user_email'  => $_SESSION['email'],
	        'msg_type'    => isset($_POST['msg_type']) ? intval($_POST['msg_type'])     : 0,
	        'msg_title'   => isset($_POST['msg_title']) ? trim($_POST['msg_title'])     : '',
	        'msg_content' => isset($_POST['msg_content']) ? trim($_POST['msg_content']) : '',
	        'order_id'	  => empty($_POST['order_id']) ? 0 : intval($_POST['order_id']),
	        'upload'      => (isset($_FILES['message_img']['error']) && $_FILES['message_img']['error'] == 0) || (!isset($_FILES['message_img']['error']) && 
	    					  isset($_FILES['message_img']['tmp_name']) && $_FILES['message_img']['tmp_name'] != 'none') ? $_FILES['message_img'] : array()
	     );
	
	    if (add_message($message)){
	        $this->redirect('/user/message_list','',2,$GLOBALS['_LANG']['add_message_success']);
	    }
	    else{
	        $this->redirect('/user/message_list','',2,$GLOBALS['_LANG']['message_list_lnk']);
	    }
    }
   
    /**
     * 用户红包
     * 
     */
    public function bonus(){
		$user_id 			=	$_SESSION['user_id']; 
	    $bonus 				= 	get_user_bouns_list($user_id);
	
	    $this->assign('bonus', $bonus);
	    $this->assign('action', 'bonus');
	    $this->display('user_bonus');
    }
    
    /**
     * 添加红包
     * Enter description here ...
     */
    public function add_bonus(){
    	
    	$user_id 		=	$_SESSION['user_id']; 
	    $bouns_sn 		= 	isset($_POST['bonus_sn']) ? intval($_POST['bonus_sn']) : '';
		
	    $add_result		=	add_bonus( $user_id, $bouns_sn );
	    
	    t($add_result);
	    
	    if ( $add_result['result'] ){
	    	$this->success( $add_result['msg'],U('user/bonus') );
	    }
	    else{
	        $this->error( $add_result['msg'] );
	    }   	
    }    
    
    /**
     * 用户评论
     * 
     */
    public function comment_list(){
		$user_id 			=	$_SESSION['user_id']; 
	    /* 获取用户留言的数量 */
	    $this->assign('comment_list', get_comment_list($user_id));
	    $this->assign('action', 'comment_list');
	    $this->display('user_comment_list');
    }
    
    /**
     * 用户账户
     * Enter description here ...
     */
    public function account_log(){
    	$user_id 			=	$_SESSION['user_id']; 
	    //获取剩余余额
	    $surplus_amount 	= 	get_user_surplus($user_id);
	    if (empty($surplus_amount)){
	        $surplus_amount = 	0;
	    }
	
	    //获取余额记录
	    $account_log 		= 	get_account_log($user_id);
	
	    //模板赋值
	    $this->assign('surplus_amount', 	price_format($surplus_amount, false));
	    $this->assign('account_log',    	$account_log);
	    $this->assign('action',    			'account_log');
	    $this->display('user_account_log');
    }
    
    /**
     * 处理编辑用户
     * Enter description here ...
     */
    public function edit_profile_ok(){
		
    	$CommonModel				=	new CommonModel();
    	
    	$user_id 					=	$_SESSION['user_id'];  // 用户id
    	
	    $birthday 					= 	trim($_POST['birthdayYear']) .'-'. trim($_POST['birthdayMonth']) .'-'.
	    trim($_POST['birthdayDay']);
	    $email 						= 	trim($_POST['email']);
	    $other['msn'] 				= 	$msn 			= 	isset($_POST['extend_field1']) ? trim($_POST['extend_field1']) : '';
	    $other['qq'] 				= 	$qq 			= 	isset($_POST['extend_field2']) ? trim($_POST['extend_field2']) : '';
	    $other['office_phone'] 		= 	$office_phone 	= 	isset($_POST['extend_field3']) ? trim($_POST['extend_field3']) : '';
	    $other['home_phone'] 		= 	$home_phone 	= 	isset($_POST['extend_field4']) ? trim($_POST['extend_field4']) : '';
	    $other['mobile_phone'] 		= 	$mobile_phone 	= 	isset($_POST['extend_field5']) ? trim($_POST['extend_field5']) : '';
	    $sel_question 				= 	empty($_POST['sel_question']) ? '' : compile_str($_POST['sel_question']);
	    $passwd_answer 				= 	isset($_POST['passwd_answer']) ? compile_str(trim($_POST['passwd_answer'])) : '';
	
	    /* 更新用户扩展字段的数据 */
	    $sql 						= 	'SELECT id FROM ' . 'ybr_reg_fields' . ' WHERE type = 0 AND display = 1 ORDER BY dis_order, id';   //读出所有扩展字段的id
	    $fields_arr 				= 	$CommonModel->query($sql);
	
	    foreach ($fields_arr AS $val){       //循环更新扩展用户信息
	        $extend_field_index 	= 	'extend_field' . $val['id'];
	        if( isset($_POST[$extend_field_index]) ){
	            $temp_field_content = 	strlen($_POST[$extend_field_index]) > 100 ? mb_substr(htmlspecialchars($_POST[$extend_field_index]), 0, 99) : htmlspecialchars($_POST[$extend_field_index]);
	            $sql 				= 	'SELECT * FROM ' . 'ybr_reg_extend_info' . "  WHERE reg_field_id = '$val[id]' AND user_id = '$user_id'";
	            if ($db->getOne($sql)){      //如果之前没有记录，则插入
	                $sql 			= 	'UPDATE ' . 'ybr_reg_extend_info' . " SET content = '$temp_field_content' WHERE reg_field_id = '$val[id]' AND user_id = '$user_id'";
	            }
	            else{
	                $sql 			= 	'INSERT INTO '. 'ybr_reg_extend_info' . " (`user_id`, `reg_field_id`, `content`) VALUES ('$user_id', '$val[id]', '$temp_field_content')";
	            }
	            $CommonModel->query($sql);
	        }
	    }
	
	    /* 写入密码提示问题和答案 */
	    if (!empty($passwd_answer) && !empty($sel_question)){
	        $sql 					= 	'UPDATE ' . 'ybr_users' . " SET `passwd_question`='$sel_question', `passwd_answer`='$passwd_answer'  WHERE `user_id`='" . $_SESSION['user_id'] . "'";
	        $CommonModel->query($sql);
	    }
		/* 手机号码,家庭号码,邮箱,MSN,qq,移动电话 -- 正则验证  */
	    if (!empty($office_phone) && !preg_match( '/^[\d|\_|\-|\s]+$/', $office_phone ) ){
	        $this->error($GLOBALS['_LANG']['passport_js']['office_phone_invalid']);   
	    }
	    if (!empty($home_phone) && !preg_match( '/^[\d|\_|\-|\s]+$/', $home_phone) ){
	        $this->error($GLOBALS['_LANG']['passport_js']['home_phone_invalid']);
	    }
	    if (!is_email($email)){
	        $this->error($GLOBALS['_LANG']['msg_email_format']);
	    }
	    if (!empty($msn) && !is_email($msn)){
	        $this->error($GLOBALS['_LANG']['passport_js']['msn_invalid']);
	    }
	    if (!empty($qq) && !preg_match('/^\d+$/', $qq)){
	        $this->error($GLOBALS['_LANG']['passport_js']['qq_invalid']);
	    }
	    if (!empty($mobile_phone) && !preg_match('/^[\d-\s]+$/', $mobile_phone)){
	        $this->error($GLOBALS['_LANG']['passport_js']['mobile_phone_invalid']);
	    }
	
	    $profile  = array(
	        'user_id'  => $user_id,
	        'email'    => isset($_POST['email']) ? trim($_POST['email']) : '',
	        'sex'      => isset($_POST['sex'])   ? intval($_POST['sex']) : 0,
	        'birthday' => $birthday,
	        'other'    => isset($other) ? $other : array()
       	);
	
		$edit_result		=	edit_profile($profile);	
       
		/* 编辑的结果 */
	  	if ( true == $edit_result['status'] ){
	        $this->success( $GLOBALS['_LANG']['edit_profile_success'],U('user/profile') );
	   	}
	   	else{
	       /*if ($User->error == ERR_EMAIL_EXISTS){
	           $msg 		= 	sprintf($GLOBALS['_LANG']['email_exist'], $profile['email']);
	       }
	       else{
	           $msg 		= 	$GLOBALS['_LANG']['edit_profile_failed'];
	       }
	       show_message($msg, '', '', 'info');*/
	       $this->error($edit_result['msg']);
	   }
    }
    
    /**
     * 处理编辑密码信息
     * Enter description here ...
     */
    public function edit_password_ok(){
    	Vendor('Integrates.ecshop');
    
	    $User					=	new Ecshop();
	    $GLOBALS['ecs']			=	& $User;
    	
	    $CommonModel			=	new CommonModel();
	    
    	$user_id 				=	$_SESSION['user_id'];  // 用户id
    	
	    $old_password 			= 	isset($_POST['old_password']) ? trim($_POST['old_password']) : null;
	    $new_password 			= 	isset($_POST['new_password']) ? trim($_POST['new_password']) : '';
	    $user_id      			= 	isset($_POST['uid'])  ? intval($_POST['uid']) : $user_id;
	    $code         			= 	isset($_POST['code']) ? trim($_POST['code'])  : '';

	    if (strlen($new_password) < 6){
	        $this->error($GLOBALS['_LANG']['passport_js']['password_shorter']);
	    }
	
	    $user_info 				= 	$User->get_profile_by_id($user_id); 	//论坛记录	 
	    
	    if ( ($user_info && (!empty($code) && md5($user_info['user_id'] . $GLOBALS['_CFG']['hash_code'] . $user_info['reg_time']) == $code)) || ($_SESSION['user_id']>0 && $_SESSION['user_id'] == $user_id && $User->check_user($_SESSION['user_name'], $old_password)) ){
			
	    	if ($User->edit_user(array('username'=> (empty($code) ? $_SESSION['user_name'] : $user_info['user_name']), 'old_password'=>$old_password, 'password'=>$new_password), empty($code) ? 0 : 1)){
				$sql			=	" UPDATE " . ' ybr_users ' . " SET `ec_salt`='0' WHERE user_id= '".$user_id."'";
				$CommonModel->query($sql);
	            $User->logout();
	            $this->redirect('/pass/login' ,'' ,1 ,$GLOBALS['_LANG']['edit_password_success']);
	        }
	        else{
	            $this->error($GLOBALS['_LANG']['edit_password_failure']);
	        }
	    }
	    else{
	        $this->error($GLOBALS['_LANG']['edit_password_failure']);
	    }	
    }
    
    /**
     * 包裹跟踪
     * Enter description here ...
     */
    public function track_packages(){
    	
    	$this->assign('action',      'track_packages');
    	
    	$this->display('user_track_packages');
    }
	
    /**
     * 发送邮件绑定用户账户
     * Enter description here ...
     */
    public function send_email(){
    	
    	$email				=	$this->_post('email');
    	$code 				=	createVerifyCode(4);
		$emailContent 		=	"您好!" . "<br/><br/>&nbsp;&nbsp;音伴尔发送给你绑定邮箱&nbsp;&nbsp; {$email} &nbsp;&nbsp;的验证码。请查看：" . "<br/><br/>&nbsp;&nbsp;&nbsp;&nbsp;" . $code . "<br/><br/>&nbsp;&nbsp;&nbsp;&nbsp;该验证码有效时间为24小时";
		$is_sended			=	$this->sendemail($email, $emailContent);
		
		if($is_sended){
			$this->ajaxReturn(1,"发送成功",1);
		}
		else {
			$this->ajaxReturn(0,"发送失败",1);
		}
    }
    
    /**
     * 验证邮箱
     * Enter description here ...
     */
    public function check_email(){
		$code 	=	md5(trim($_REQUEST['code']));
		$email 	=	trim($_REQUEST['email']);
		
		if(md5($_SESSION['code']) == $code){	
			$datas['email']			=	$email;
			$datas['is_validated']	=	1;
			M('Users')->where("user_id = '{$_SESSION['user_id']}'")->save($datas);			
			$this->ajaxReturn(1,'',1);
		}
		else{
			$this->ajaxReturn(1,'',1);
		}
    }
    
	/**
	 * 发送邮件函数
	 * @param unknown $toemail
	 * @param unknown $emailcontent
	 * @return boolean
	 * 
	 */
	private function sendemail($toemail,$emailcontent){
	
		$subject 		= 	'主题：音伴尔';
		/****** 第一种:qq 
		# smtp服务器地址, 如smtp.qq.com
		$host 			=	'smtp.qq.com'; //qq邮箱服务器
		//$host 			=	'smtp.163.com'; //qq邮箱服务器
		# 发件人名称
		$fromname 		=	'环听网';
		# 发件人地址和收件人地址填你的邮箱
		$from 			= 	'1039286629@qq.com';
		$to 			= 	$toemail;
		# 你邮箱账号
		$username 		=	$from;
		$passwd 		= 	'2231125593';
		*/		
		# smtp服务器地址, 如smtp.qq.com
		// $host 			=	'smtp.qq.com';
		// # 发件人名称
		// $fromname 		=	'环听网';
		// # 发件人地址和收件人地址填你的邮箱
		// $from 			= 	'823662722@qq.com';
		// $to 			= 	$toemail;
		// # 你邮箱账号
		// $username 		=	$from;
		// $passwd 		= 	'2008wer167.';
		# smtp服务器地址, 如smtp.qq.com
		//$host 			=	'smtp.qq.com'; //qq邮箱服务器
		$host 			=	'smtp.163.com'; //qq邮箱服务器
		# 发件人名称
		$fromname 		=	'音伴尔官网';
		# 发件人地址和收件人地址填你的邮箱
		$from 			= 	'yinbaner@163.com';
		$to 			= 	$toemail;
		# 你邮箱账号
		$username 		=	$from;
		$passwd 		= 	'lrc717120';
		
		$mailer 		=	new PHPMailer(true);
		$mailer->IsHTML(true);//是否支持html邮件
		$mailer->IsSMTP(true);//
		//$mailer->SMTPDebug = true;
		$mailer->CharSet  = 'UTF-8';
		$mailer->Encoding = 'base64';
		$mailer->FromName = $fromname;
		$mailer->Host     = $host;//SMTP服务器地址
		$mailer->AddAddress($to);
		$mailer->From     = $from;
		$mailer->Subject  = $subject;
		$mailer->MsgHTML($emailcontent);
		$mailer->SMTPAuth = true;//设置为安全验证方式
		$mailer->Username = $username;
		$mailer->Password = $passwd;
		try{
			$mailer->Send();
			return true;
		} catch (phpmailerException $e) {
			print_r($e);
			return false;
		}
	}
    
    
    
    
    
    
    
    
}






